const app = getApp()
import { list, receive } from '../../api/coupon'

Page({
  data: {
    back: true,
    title: '领卷中心',
    loading: true,
    loadmore: false,
    login: false,
    list: null,
    couponShowType: 10,
    form: {
      page: 1,
      limit: 10
    },
    abnor: {
      title: '哎呀，来晚了~',
      button: '先去逛逛'
    }
  },
  onLoad () {
    this.setData({ loading: true })
    this.getList()
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () {
    if (this.data.form.page == this.data.form.last_page) {
      this.setData({ loadmore: true })
    } else {
      this.data.form.page += 1
      this.getList()
    }
  },

  // ===================methon================

  getList (res) {
    list(this.data.form).then(res => {
      const { data } = res
      this.data.list || (this.data.list = [])
      const list = this.data.list.concat(data.data)
      this.data.form.last_page = res.data.last_page
      this.setData({
        list: list,
        loadmore: data.last_page <= 1
      })
    })
      .finally(() => {
        this.setData({ loading: false })
        wx.hideLoading()
      })
  },

  handleReceive (event) {
    if (app.login()) {
      const id = event.currentTarget.dataset.id
      receive(id).then(res => {
        app.toast(res.msg, null, 'success')
      })
        .catch(e => {
          app.toast(e.msg)
        })
    } else {
      this.setData({ login: true })
    }
  },

  onAbnor () {
    app.redirect('/pages/goods/index/index')
  }
})